#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include "n2link.h"
#include "SectionTab.h"

TSection::TSection()
{
    for (int i = 0; i < 8; i++)
        m_SecName.name[i] = 0;
    m_SecNameLength = 0;
    m_OffsetInObj = 0;
    m_SecDataSize = 0;
    m_Flags = 0;
    m_RelInfoOffset = 0;
    m_RelInfoCount = 0;
    m_GlobalSectionId = 0;
    m_ObjFileIndex = 0xffffffff;
    m_RelInfoTab = NULL;
}

TSection::~TSection()
{
    if (m_RelInfoTab) {
        delete[] m_RelInfoTab;
        m_RelInfoTab = NULL;
    }
}

TSection::TSection(const Coff32_Shdr *pCoff32Section, const char * name)
{
    m_SecNameLength = (unsigned) strlen(name);
    if (m_SecNameLength < 8) {
        strcpy(m_SecName.name, name);
        m_SecName.name[7] = 0;
    }
    else {
        m_SecName.offset =  strpool.AddStr(name);
    }

    m_OffsetInObj = pCoff32Section->raw_offset;
    m_SecDataSize = pCoff32Section->raw_size;
    m_Flags = pCoff32Section->flag;
    m_RelInfoOffset = pCoff32Section->relinfo_offset;
    m_RelInfoCount = pCoff32Section->relinfo_count;

    m_GlobalSectionId = 0;
    m_ObjFileIndex = 0xffffffff;
    m_RelInfoTab = NULL;
}

void TSection::MoveFrom(TLinkerUniverTabItem *p)
{
    TSection * pSec;
    pSec = static_cast <TSection *> (p);

    for (int i = 0; i < 8; i++) {
        m_SecName.name[i] = pSec->m_SecName.name[i];
    }
    m_SecNameLength = pSec->m_SecNameLength;
    m_OffsetInObj = pSec->m_OffsetInObj;
    m_SecDataSize = pSec->m_SecDataSize;
    m_Flags = pSec->m_Flags;
    m_RelInfoOffset = pSec->m_RelInfoOffset;
    m_RelInfoCount = pSec->m_RelInfoCount;
    m_GlobalSectionId = pSec->m_GlobalSectionId;
    m_ObjFileIndex = pSec->m_ObjFileIndex;
    m_RelInfoTab = pSec->m_RelInfoTab;
}

TLinkerUniverTabItem * TSection::GetOffsetItem(size_t index)
{
    return & this[index];
}

unsigned int TSection::GetAlignValue()
{
    unsigned int index;
    static unsigned short align[] = {1,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,1};
    index = m_Flags & 0x00F00000;
    index >>= 20;
    return align[index];
}

TLinkerUniverTabItem* TSectionTab::AllocGroupData(size_t count)
{
    return new TSection[count];
}

TSection* TSectionTab::GetSection(size_t index)
{
    return static_cast <TSection *> (GetItem(index));
}

TSectionTab::TSectionTab(size_t _group_base)
    : TLinkerUniverTab(_group_base)
{
}

TSectionTab * allsections;









